package indi.mozping.pc;

import indi.mozping.tools.SleepTools;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author by mozping
 * @Classname PcCondition
 * @Description TODO
 * @Date 2019/8/12 17:36
 */
public class PcCondition {

    private static ReentrantLock lock = new ReentrantLock();
    private static Condition consumer = lock.newCondition();
    private static Condition producer = lock.newCondition();
    private static LinkedList<Object> buffer = new LinkedList<>();
    private static final int MAX = 5;

    public static void main(String[] args) {
        new Thread(new Producer()).start();
        new Thread(new Producer()).start();
        new Thread(new Consumer()).start();
        new Thread(new Consumer()).start();
    }


    static class Producer implements Runnable {

        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    while (buffer.size() >= MAX) {
                        System.out.println("����...");
                        try {
                            producer.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (buffer.size() < MAX) {
                        buffer.add(new Object());
                        System.out.println("����һ��...������������" + buffer.size());
                        consumer.signalAll();
                        SleepTools.randomMs(5000);
                    }
                } finally {
                    lock.unlock();
                }
                //�����һ������������֮��һֱ�ظ���ȡ��������������֮��Ż��������߿�ʼ����
                SleepTools.randomMs(5);
            }
        }
    }

    static class Consumer implements Runnable {

        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    while (buffer.size() <= 0) {
                        System.out.println("����...");
                        try {
                            consumer.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (buffer.size() > 0) {
                        buffer.removeFirst();
                        System.out.println("����һ��...���Ѻ�������" + buffer.size());
                        producer.signalAll();
                        SleepTools.randomMs(5000);
                    }
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}